﻿#region 信息

// Copyright©2014 Rex Rao all rights reserved.
// File name : SoMcCoffee\Sohobloo.SoMcCoffee\EfDbContext.cs
// Author : Sohobloo
// Create time : 2014/01/31 23:40
// Update time : 2014/02/05 8:56

#endregion

#region 引用

using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using Sohobloo.SoCommon.CommonExtension;
using Sohobloo.SoCommon.Log;
using Sohobloo.SoMcCoffee.Entity;

#endregion

namespace Sohobloo.SoMcCoffee.Data
{
    /// <summary>
    ///     EF数据访问上下文
    /// </summary>
    [Export(typeof(DbContext))]
    public class EfDbContext : DbContext, ILoggable
    {
        private const string ConnectionName = "DefaultConnection";

        [Import]
        public ILogger Logger { get; set; }

        public EfDbContext()
            : base(ConnectionName)
        {
            Database.Log = this.TraceSql;
        }

        public EfDbContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
            Database.Log = this.TraceSql;
        }

        [ImportMany]
        private IEnumerable<IEntityMapper> EntityMappers { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //移除复数表名
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            //移除一对多的级联删除约定，想要级联删除可以在 EntityTypeConfiguration<TEntity>的实现类中进行控制
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

            if(Configuration.IsNotNull())
            {
                foreach(var mapper in EntityMappers)
                {
                    mapper.RegistTo(modelBuilder.Configurations);
                }
            }
        }
    }
}